// pages/mall/cart/cart.js
const app = getApp();
var spManger = require('../../data/ShopCartManager.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    allSelected: {
      checked: false,
      num: 0
    },
    sendData: [],
    shouquan: false,
    totalPrice: 0,
    edit: false,
    editTxt: '编辑',
    MobileShoppingCartGetList: null,
    storeName: '和助力商城'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.checkLogin_getData();
    wx.hideShareMenu();
  },
  btnSettlementClick: function() {
    if (this.data.sendData.length <= 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: "/pages/order/order?carGoodsList=" + JSON.stringify(this.data.sendData)
    }) + "&isnowbuy=0";
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
    var that = this;
    this.setData({
      editTxt: '编辑'
    });
    this.setData({
      sendData: [],
      edit: false,
      'allSelected.num': 0
    });
    this.data.totalPrice = 0;
    //从缓存取出购物车商品
    wx.getStorage({
      key: 'shopCart',
      success: function(res) {
        console.log(res);
        wx.showLoading({
          title: '读取购物车信息中...',
        })
        var _skuids = spManger.ShopCartManagerClass.Instance.ConvertToSkuids(res.data);
        if(_skuids==""){
          wx.hideLoading();
          that.setData({
            MobileShoppingCartGetList: res.data,
            storeName: app.globalData.userInfo.ShopName
          });
          return false;
        }
         
        wx.request({
          url: app.appSetting.host + "/ShopCart?userid=" + app.globalData.userInfo.Id + "&token=" + app.globalData.userInfo.Token + "&skuids=" + _skuids,
          data: {},
          method:"GET",
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function(resData) {
            console.log(resData);
            wx.hideLoading();
            if (resData.statusCode==200) {
                //将sku模型赋值
              res.data = spManger.ShopCartManagerClass.Instance.GetFullSkuModel(res.data,resData.data);
              console.log(res.data);
              that.setData({
                MobileShoppingCartGetList:res.data,
                storeName:app.globalData.userInfo.ShopName
              });
              //循环商品是否全选中
              that.data.MobileShoppingCartGetList.forEach((value, index) => {
                if (value.State != 0) {
                  that.data.allSelected.num++;
                  that.data.sendData.push(value);
                  that.data.totalPrice += Number(value.SkuDetail.SallPrice).toFixed(2) * value.SaleNum;
                }
              })
              that.setData({
                totalPrice: that.data.totalPrice.toFixed(2),
              });
              if (that.data.allSelected.num == that.data.MobileShoppingCartGetList.length) {
                that.setData({
                  allSelected: {
                    checked: true,
                  }
                });
              }
            }else{
              wx.showToast({
                title: resData.data,
                icon: 'none'
              })
            }
          }
        })
      }
    })
   


  },
  //检测登录
  checkLogin_getData: function () {
    let self = this;
      wx.getStorage({
        key: 'seltUser',
        success: function (res) {
          if (app.globalData.userInfo == null)
            app.globalData.userInfo = res.data;
        },
        fail: function (res) {
          self.setData({
            shouquan: true
          });
        }
      })
  },

  getUserInfo: function (res) {
    let self = this;
    // 登录 
    wx.login({
      success: function (_res) {
        //获取用户信息
        wx.request({
          method: 'POST',
          url: app.appSetting.host + '/User/login/app',
          data: {
            Spid: app.appSetting.spid,
            HeadImgUrl: res.detail.userInfo.avatarUrl,
            Sex: res.detail.userInfo.gender,
            NickName: res.detail.userInfo.nickName,
            Code: _res.code,
            AppType: 1
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (result) {
            if (result.statusCode == 200) {
              app.globalData.userInfo = result.data;
              wx.setStorage({
                key: 'seltUser',
                data: result.data,
                success: function (res) {
                  self.setData({
                    shouquan: false
                  });
                  
                }
              })
            } else {
              wx.showToast({
                title: result.data,
                icon: 'none'
              })
            }
          },
          complete: function (res) { }
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
      //更新购物车缓存
    var list = this.data.MobileShoppingCartGetList;
    if(list==null)
      return false;
    //简版
    list = spManger.ShopCartManagerClass.Instance.GetEasySkuModelList(list);
    //更新缓存
    wx.setStorage({
      key: 'shopCart',
      data: list,
      success:function(res){
        console.log(res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
      //更新购物车缓存
    //更新购物车缓存
    var list = this.data.MobileShoppingCartGetList;
    if (list == null)
      return false;
    //简版
    list = spManger.ShopCartManagerClass.Instance.GetEasySkuModelList(list);
    //更新缓存
    wx.setStorage({
      key: 'shopCart',
      data: list,
      success: function (res) {
        console.log(res);
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 获取多选框list中选中的值和对应的id
  checkboxChange: function(e) {
    this.data.totalPrice = 0;
    this.data.sendData = [];
    var text = [];
    var id = [];
    for (var i = 0; i < e.detail.value.length; i++) {
      var aaa = e.detail.value[i].split(',');
      id = id.concat(aaa[0])
    }
    //把数据储存在变量中
    id.forEach((value, index) => {
      this.data.sendData.push(this.data.MobileShoppingCartGetList[value]);
      this.data.totalPrice += Number(this.data.MobileShoppingCartGetList[value].SkuDetail.SallPrice).toFixed(2) * this.data.MobileShoppingCartGetList[value].SaleNum;

    })

    if (id.length == this.data.MobileShoppingCartGetList.length) {
      this.setData({
        allSelected: {
          checked: true,
        },
        totalPrice: this.data.totalPrice.toFixed(2)
      });
      return
    } else {
      this.setData({
        allSelected: {
          checked: false,
        },
        totalPrice: this.data.totalPrice.toFixed(2)
      });
      return
    }

  },

  radioChange(e) {
    this.data.totalPrice = 0;
    this.data.sendData = [];
    if (e.detail.value.length > 0) {
      this.data.MobileShoppingCartGetList.forEach((value, index) => {
        value.State = 1;
        // this.data.totalPrice += this.mul(Number(value.SalePrice), value.SaleNum) ;
        this.data.totalPrice += Number(value.SkuDetail.SallPrice).toFixed(2) * value.SaleNum;
        this.data.sendData.push(value);
        
      })
      this.setData({
        allSelected: {
          checked: true,
        },
        totalPrice: this.data.totalPrice.toFixed(2)
      })
    } else {
      this.data.MobileShoppingCartGetList.forEach((value, index) => {
        value.State = 0;
      })
      this.setData({
        allSelected: {
          checked: false,
        },
        totalPrice: this.data.totalPrice.toFixed(2)
      })
    }
    this.setData({
      MobileShoppingCartGetList: this.data.MobileShoppingCartGetList,
    })
  },

  edit() {
    this.data.edit = !this.data.edit;
    this.data.editTxt = this.data.edit ? '完成' : '编辑'
    this.setData({
      edit: this.data.edit,
      editTxt: this.data.editTxt
    });
  },

  deleteCart(ev) {
    let self = this;
    wx.showModal({
      title: '确认删除此商品吗？',
      content: '',
      success: function(res) {
        if (res.confirm) {
          self.data.sendData = [];
          self.data.allSelected.num = 0;
          self.data.totalPrice = 0;
          var _product_skuid = ev.currentTarget.dataset.cart.Product_SkuId;
          var _list = spManger.ShopCartManagerClass.Instance.DeleteSkuBySkuId(self.data.MobileShoppingCartGetList,_product_skuid);
          self.setData({
            MobileShoppingCartGetList: _list
          });
          //循环商品是否全选中
          self.data.MobileShoppingCartGetList.forEach((value, index) => {
            if (value.State != 0) {
              self.data.allSelected.num++;
              self.data.sendData.push(value);
              self.data.totalPrice += Number(value.SkuDetail.SallPrice).toFixed(2) * value.SaleNum;
            }
          })

          self.setData({
            totalPrice: self.data.totalPrice,
          });
          if (self.data.allSelected.num == self.data.MobileShoppingCartGetList.length) {
            self.setData({
              allSelected: {
                checked: true,
              }
            });
          }


         
        } else if (res.cancel) {}
      }
    })
  },

  updateState(ev) {
    if (!ev.currentTarget.dataset.cartinfo.State) {
      ev.currentTarget.dataset.cartinfo.State = 1;
    } else {
      ev.currentTarget.dataset.cartinfo.State = 0;
    }
    var skuid = ev.currentTarget.dataset.cartinfo.Product_SkuId;
    var skumodel = spManger.ShopCartManagerClass.Instance.GetModelBySkuId(this.data.MobileShoppingCartGetList, skuid);
    skumodel.State = ev.currentTarget.dataset.cartinfo.State;
    spManger.ShopCartManagerClass.Instance.UpdateSkuModel(this.data.MobileShoppingCartGetList,skumodel);
    this.setData({
      MobileShoppingCartGetList: this.data.MobileShoppingCartGetList
    });
  },

  //添加数量

  addNum(ev) {
    this.data.sendData = [];
    if (ev.currentTarget.dataset.cartinfo.SaleNum >= ev.currentTarget.dataset.cartinfo.SkuDetail.StockNum) {
      wx.showToast({
        title: '不能超过库存',
        icon: 'none'
      })
      return
    }
    var skuid = ev.currentTarget.dataset.cartinfo.Product_SkuId;
    var skumodel = spManger.ShopCartManagerClass.Instance.GetModelBySkuId(this.data.MobileShoppingCartGetList, skuid);
    skumodel.SaleNum = skumodel.SaleNum+1;
    spManger.ShopCartManagerClass.Instance.UpdateSkuModel(this.data.MobileShoppingCartGetList, skumodel);
    this.setData({
      MobileShoppingCartGetList: this.data.MobileShoppingCartGetList
    });
    this.data.totalPrice = 0;
    //循环商品是否全选中
    this.data.MobileShoppingCartGetList.forEach((value, index) => {
      if (value.State != 0) {
        this.data.allSelected.num++;
        this.data.sendData.push(value);
        // this.data.totalPrice += Number(value.SalePrice) * value.SaleNum;
        this.data.totalPrice += Number(value.SkuDetail.SallPrice).toFixed(2) * value.SaleNum;
      }
    })
    this.setData({
      totalPrice: this.data.totalPrice.toFixed(2),
    });
    if (this.data.allSelected.num == this.data.MobileShoppingCartGetList.length) {
      this.setData({
        allSelected: {
          checked: true,
        }
      });
    }
    
  },

  delNum(ev) {
    this.data.sendData = [];
    if (ev.currentTarget.dataset.cartinfo.SaleNum <= 1) {
      wx.showToast({
        title: '最少购买一件',
        icon: 'none'
      })
      return
    }
    var skuid = ev.currentTarget.dataset.cartinfo.Product_SkuId;
    var skumodel = spManger.ShopCartManagerClass.Instance.GetModelBySkuId(this.data.MobileShoppingCartGetList, skuid);
    skumodel.SaleNum = skumodel.SaleNum - 1;
    spManger.ShopCartManagerClass.Instance.UpdateSkuModel(this.data.MobileShoppingCartGetList, skumodel);
    this.setData({
      MobileShoppingCartGetList: this.data.MobileShoppingCartGetList
    });
    this.data.totalPrice = 0;

    //循环商品是否全选中
    this.data.MobileShoppingCartGetList.forEach((value, index) => {
      if (value.State != 0) {
        this.data.allSelected.num++;
        this.data.sendData.push(value);
        this.data.totalPrice += Number(value.SkuDetail.SallPrice).toFixed(2) * value.SaleNum
        // this.data.totalPrice  += this.mul(Number(value.SalePrice), value.SaleNum );
        // this.data.totalPrice = this.mul(Number(value.SalePrice), value.SaleNum );
      }
    })
    this.setData({
      totalPrice: this.data.totalPrice.toFixed(2),
    });
    if (this.data.allSelected.num == this.data.MobileShoppingCartGetList.length) {
      this.setData({
        allSelected: {
          checked: true,
        }
      });
    }

   
  },

  goToDetail(ev) {
    // wx.navigateTo({
    //   url: "/pages/mall/detail/detail?id=" + ev.currentTarget.dataset.goodsinfo.ProductID,
    // })
  },


  add(arg1, arg2) {
    var r1, r2, m, c;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
      var cm = Math.pow(10, c);
      if (r1 > r2) {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", "")) * cm;
      } else {
        arg1 = Number(arg1.toString().replace(".", "")) * cm;
        arg2 = Number(arg2.toString().replace(".", ""));
      }
    } else {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
  },

  /** ** 乘 **/
  mul(arg1, arg2) {
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) {}
    try {
      m += s2.split(".")[1].length;
    } catch (e) {}
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  }


})